package logic

import (
	"beike/cache"
	"beike/houserpc/houserpc"
	"beike/houserpc/internal/svc"
	"beike/models"
	"context"
	"fmt"
	"math/rand"
	"strconv"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *houserpc.LoginRequest) (*houserpc.LoginResponse, error) {
	// todo: add your logic here and delete this line

	code := rand.Intn(9000) + 1000
	newCode := strconv.Itoa(code)

	var user models.User

	result, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.Mobile).Result()
	if result == "" {
		return nil, fmt.Errorf("你还未发送短信")
	}
	if result != in.SendSms {
		return nil, fmt.Errorf("短信验证码错误")
	}

	models.DB.Debug().Where("mobile = ?", in.Mobile).Find(&user)
	if user.ID == 0 {
		user = models.User{
			Mobile:   in.Mobile,
			Password: in.Password,
			NickName: "默认用户" + newCode,
			HeadImg:  "https://c-ssl.dtstatic.com/uploads/item/202004/14/20200414210134_qbeyi.thumb.400_0.jpg",
		}
		models.DB.Debug().Create(&user)
	} else {
		if in.Password != user.Password {
			return nil, fmt.Errorf("密码错误，请重新输入")
		}
	}

	return &houserpc.LoginResponse{
		UserId: int64(user.ID),
	}, nil
}
